//
//  GoldenVPNLoginVC.m
//  QLadder
//
//  Created by xiongguobing on 2019/8/8.
//  Copyright © 2019 qding. All rights reserved.
//

#import "GoldenVPNLoginVC.h"
#import "GoldenVPNRegistVC.h"
#import "GoldenVPNForgetPwdVC.h"
#import "QLadder-Swift.h"
#import "NSString+VerifyString.h"
#import "IPToolManager.h"
#import <CoreLocation/CoreLocation.h>

@interface GoldenVPNLoginVC ()<CLLocationManagerDelegate>
@property (weak, nonatomic) IBOutlet UIView *subContentView;
@property (weak, nonatomic) IBOutlet UITextField *phoneTF;
@property (weak, nonatomic) IBOutlet UITextField *passwordTF;

@property (nonatomic, strong) NSString * currentCity;
@property (nonatomic, strong) NSString * ip;

@property (nonatomic, strong) CLLocationManager * locationManager;

@property (nonatomic, strong) GoldenVPNRegistVC * registVC;

@end

@implementation GoldenVPNLoginVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    for (UIView * subView in self.subContentView.subviews) {
        if ([subView isKindOfClass:[UITextField class]]) {
            UITextField * tf = (UITextField *)subView;
            [tf setValue:ThemeColor forKeyPath:@"_placeholderLabel.textColor"];
        }
    }
    if ([kUserDefaults objectForKey:kUserAccount]) {
        self.phoneTF.text = [kUserDefaults objectForKey:kUserAccount];
    }
    if ([kUserDefaults objectForKey:kUserPassword]) {
        self.passwordTF.text = [kUserDefaults objectForKey:kUserPassword];
    }
    self.title = @"登录";
    
    self.currentCity = self.ip = @"";
    [self getIPAndCity];
    
    self.registVC = [GoldenVPNRegistVC new];
    
    if ([CLLocationManager locationServicesEnabled]) {
        [self.locationManager startUpdatingLocation];
    }
    // Do any additional setup after loading the view from its nib.
}

- (IBAction)loginButton:(id)sender
{
    if (!ValidStr(self.phoneTF.text)) {
        kShowWithString(@"请输入用户名");
        return;
    }
    if (!ValidStr(self.passwordTF.text) || ![self.passwordTF.text verifyWithPassword]) {
        kShowWithString(@"请输入符合规则的密码");
        return;
    }
    kDismissKeyboard;
    
    [kNetworkUtil postWithModuleURLStr:userLogin parameters:@{@"userName" : self.phoneTF.text, @"passWord" : self.passwordTF.text} success:^(id response) {
        if ([[response objectForKey:@"code"] integerValue] == 200) {
            [kUserDefaults setObject:self.phoneTF.text forKey:kUserAccount];
            [kUserDefaults setObject:self.passwordTF.text forKey:kUserPassword];
            [kUserDefaults synchronize];
            [self uploadLoginLog];
        }
    } failure:nil withHud:YES];
}

- (IBAction)gotoRegistButton:(id)sender
{
    kWeakSelf(self);
    self.registVC.block = ^(NSString * _Nonnull account, NSString * _Nonnull pwd) {
        weakself.phoneTF.text = account;
        weakself.passwordTF.text = pwd;
    };
    [self.navigationController pushViewController:self.registVC animated:YES];
}

- (IBAction)forgetPasswordButtonClicked:(id)sender
{
    GoldenVPNForgetPwdVC * forgetVC = [GoldenVPNForgetPwdVC new];
    [self.navigationController pushViewController:forgetVC animated:YES];
}

- (void)uploadLoginLog
{
    NSString * userName = [kUserDefaults objectForKey:kUserAccount];
    if (!userName) {
        return;
    }
    if (!self.ip.length) {
        IPToolManager *ipManager = [IPToolManager sharedManager];
        NSString * ip = [ipManager currentIpAddress];
        self.ip = ip ?: @"-1";
    }
    NSString * cityAreaCode = self.currentCity;
    NSString * forceClose = @"0";
    NSString * imei = @"-1";
    NSString * imsi = @"-1";
    NSString * port = [NSString stringWithFormat:@"%ld", (long)[kUserDefaults integerForKey:@"randomPort"]];
    
    NSString * thisTime = [NSString stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970]];
    NSString * timeKey = @"loginTime";
    
    NSString * mac = @"wap";
    
    NSDictionary * dic = @{@"cityAreaCode" : cityAreaCode, @"forceClose" : forceClose, @"imei" : imei, @"imsi" : imsi, @"ip" : self.ip, @"loginName" : userName, timeKey : thisTime, @"mac" : mac, @"port" : port};
    [kNetworkUtil postWithModuleURLStr:userLoginLog parameters:dic success:^(id response) {
        [self dismissVC];
    } failure:nil withHud:NO];
}

- (void)getIPAndCity
{
    kWeakSelf(self);
    [NetworkManager.sharedManager getIPAndCity:^(NSString * _Nullable ip, NSString * _Nonnull currentCity) {
        weakself.ip = ip;
        
    }];
}

- (void)dismissVC
{
    if ([kAppWindow.rootViewController isKindOfClass:[UITabBarController class]]) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }else{
        QLTabBarController * tab = [[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"QLTabBarController"];
        kAppWindow.rootViewController = tab;
    }
}


#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    if (locations.count) {
        CLLocation * location = locations.lastObject;
        CLGeocoder * geo = [CLGeocoder new];
        [geo reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            NSLog(@"address is %@", [[placemarks lastObject] addressDictionary]);
            if (placemarks.count) {
                CLPlacemark * mark = placemarks.firstObject;
                self.currentCity = mark.locality;
                self.registVC.currentCity = mark.locality;
            }
        }];
    }
    [manager stopUpdatingLocation];
}

#pragma mark - setter and getter
- (CLLocationManager *)locationManager
{
    if (!_locationManager) {
        _locationManager = [CLLocationManager new];
        _locationManager.delegate = self;
        [_locationManager requestWhenInUseAuthorization];
    }
    return _locationManager;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
